<template>
  <view class="add-product-container">

    <!-- 表单内容 -->
    <scroll-view class="form-scroll" scroll-y="true">
      <!-- 商品基础信息 -->
      <view class="section">
        <view class="section-title">
          <text class="section-title-text">商品基础信息</text>
        </view>
        
        <!-- 供应商 -->
        <view class="form-item">
          <text class="label required">供应商：</text>
          <view class="picker-content">
            <text class="picker-text">{{ supplierOptions[supplierIndex] || '暂无供应商' }}</text>
          </view>
        </view>

        <!-- 品牌 -->
        <view class="form-item">
          <text class="label">品牌：</text>
          <input 
            class="input" 
            type="text" 
            placeholder="请输入品牌" 
            v-model="formData.brand"
          />
        </view>

        <!-- 商品名称 -->
        <view class="form-item">
          <text class="label required">商品名称：</text>
          <input 
            class="input" 
            type="text" 
            placeholder="请输入商品名称" 
            v-model="formData.productName"
          />
        </view>

        <!-- 销售单位 -->
        <view class="form-item">
          <text class="label">销售单位：</text>
          <input 
            class="input" 
            type="text" 
            placeholder="请输入销售单位" 
            v-model="formData.salesUnit"
          />
        </view>

        <!-- 箱规 -->
        <view class="form-item">
          <text class="label">箱规：</text>
          <input 
            class="input" 
            type="digit" 
            placeholder="请输入件/箱" 
            v-model="formData.boxSpec"
          />
          <text class="unit">件/箱</text>
        </view>

        <!-- 商品条码 -->
        <view class="form-item">
          <text class="label">商品条码：</text>
          <input 
            class="input" 
            type="text" 
            placeholder="请输入商品条码" 
            v-model="formData.barcode"
          />
        </view>

        <!-- 分类 -->
        <view class="form-item">
          <text class="label">分类：</text>
          <view class="picker" @click="openCategoryModal">
            <view class="picker-content">
              <text class="picker-text">{{ categoryText || '请选择分类' }}</text>
              <text class="picker-arrow">›</text>
            </view>
          </view>
        </view>

        <!-- 存储类型 -->
        <view class="form-item">
          <text class="label required">存储类型：</text>
          <picker 
            class="picker" 
            mode="selector" 
            :range="storageTypeOptions" 
            @change="onStorageTypeChange"
            :value="storageTypeOptions.indexOf(formData.storageType)"
          >
            <view class="picker-content">
              <text class="picker-text">{{ formData.storageType || '请选择存储类型' }}</text>
              <text class="picker-arrow">›</text>
            </view>
          </picker>
        </view>

        <!-- 辅助编码 -->
        <view class="form-item">
          <text class="label">辅助编码：</text>
          <input 
            class="input" 
            type="text" 
            placeholder="请输入辅助编码" 
            v-model="formData.auxiliaryCode"
          />
        </view>

        <!-- 商品类型 -->
        <view class="form-item">
          <text class="label required">商品类型：</text>
          <picker 
            class="picker" 
            mode="selector" 
            :range="productTypeOptions" 
            @change="onProductTypeChange"
            :value="productTypeOptions.indexOf(formData.productType)"
          >
            <view class="picker-content">
              <text class="picker-text">{{ formData.productType || '请选择商品类型' }}</text>
              <text class="picker-arrow">›</text>
            </view>
          </picker>
        </view>

        <!-- 存储条件 -->
        <view class="form-item">
          <text class="label">存储条件：</text>
          <picker 
            class="picker" 
            mode="selector" 
            :range="storageConditionOptions" 
            @change="onStorageConditionChange"
            :value="storageConditionOptions.indexOf(formData.storageCondition)"
          >
            <view class="picker-content">
              <text class="picker-text">{{ formData.storageCondition || '请选择存储条件' }}</text>
              <text class="picker-arrow">›</text>
            </view>
          </picker>
        </view>

        <!-- 保质期相关 -->
        <view class="form-item">
          <text class="label required">保质期单位：</text>
          <picker 
            class="picker" 
            mode="selector" 
            :range="shelfLifeUnitOptions" 
            @change="onShelfLifeUnitChange"
            :value="shelfLifeUnitOptions.indexOf(formData.shelfLifeUnit)"
          >
            <view class="picker-content">
              <text class="picker-text">{{ formData.shelfLifeUnit || '请选择保质期单位' }}</text>
              <text class="picker-arrow">›</text>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label required">保质期：</text>
          <input 
            class="input" 
            type="number" 
            placeholder="请输入保质期" 
            v-model="formData.shelfLife"
          />
        </view>

        <!-- 重量 -->
        <view class="form-item">
          <text class="label required">重量(KG)：</text>
          <input 
            class="input" 
            type="digit" 
            placeholder="请输入重量" 
            v-model="formData.weight"
          />
          <text class="unit">KG</text>
        </view>

        <!-- 规格尺寸 -->
        <view class="form-item">
          <text class="label required">规格长(CM)：</text>
          <input 
            class="input" 
            type="digit" 
            placeholder="请输入长度" 
            v-model="formData.specLength"
          />
          <text class="unit">CM</text>
        </view>

        <view class="form-item">
          <text class="label required">规格宽(CM)：</text>
          <input 
            class="input" 
            type="digit" 
            placeholder="请输入宽度" 
            v-model="formData.specWidth"
          />
          <text class="unit">CM</text>
        </view>

        <view class="form-item">
          <text class="label required">规格高(CM)：</text>
          <input 
            class="input" 
            type="digit" 
            placeholder="请输入高度" 
            v-model="formData.specHeight"
          />
          <text class="unit">CM</text>
        </view>

        

        <!-- 实拍图 -->
        <view class="form-item image-upload-item">
          <text class="label">实拍图：</text>
          <view class="image-upload-container">
            <view class="image-list">
              <view 
                class="image-item" 
                v-for="(image, index) in formData.productImages" 
                :key="index"
              >
                <image 
                  class="uploaded-image" 
                  :src="image" 
                  mode="aspectFill"
                  @click="previewImage(index)"
                />
                <view class="delete-btn" @click="deleteImage(index)">
                  <text class="delete-icon">×</text>
                </view>
              </view>
              
              <view 
                class="upload-btn" 
                @click="chooseImage"
              >
                <text class="upload-icon">+</text>
                <text class="upload-text">上传图片</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 托规 -->
        <view class="form-item">
          <text class="label required">托规：</text>
          <input 
            class="input" 
            type="text" 
            placeholder="请输入托规" 
            v-model="formData.palletSpec"
          />
        </view>

        <!-- 成本 -->
        <view class="form-item">
          <text class="label required">成本：</text>
          <input 
            class="input" 
            type="digit" 
            placeholder="请输入成本" 
            v-model="formData.cost"
          />
          <text class="unit">元</text>
        </view>

        <!-- 计费方式 -->
        <view class="form-item">
          <text class="label required">计费方式：</text>
          <picker 
            class="picker" 
            mode="selector" 
            :range="billingMethodOptions" 
            @change="onBillingMethodChange"
            :value="billingMethodOptions.indexOf(formData.billingMethod)"
          >
            <view class="picker-content">
              <text class="picker-text">{{ formData.billingMethod || '请选择计费方式' }}</text>
              <text class="picker-arrow">›</text>
            </view>
          </picker>
        </view>

        <!-- 是否需要质检 -->
        <view class="form-item">
          <text class="label">是否需要质检：</text>
          <picker 
            class="picker" 
            mode="selector" 
            :range="needQualityCheckOptions" 
            @change="onNeedQualityCheckChange"
            :value="needQualityCheckOptions.indexOf(formData.needQualityCheck)"
          >
            <view class="picker-content">
              <text class="picker-text">{{ formData.needQualityCheck || '请选择是否需要质检' }}</text>
              <text class="picker-arrow">›</text>
            </view>
          </picker>
        </view>
      </view>
      
      <!-- 底部留白 -->
      <view class="bottom-spacing"></view>
    </scroll-view>
    
    <!-- 分类选择弹窗 -->
    <view class="category-modal" v-if="showCategoryModal" @click="showCategoryModal = false">
      <view class="category-modal-content" @click.stop>
        <view class="category-modal-header">
          <text class="category-modal-title">选择分类</text>
          <text class="category-modal-close" @click="showCategoryModal = false">×</text>
        </view>
        
        <scroll-view class="category-modal-body" scroll-y="true">
          <radio-group @change="onRadioChange">
            <view class="category-tree">
              <block v-for="(item, index) in categoryData" :key="index">
              <view class="category-node-wrapper">
                <view 
                  class="category-node" 
                  :style="{paddingLeft: '20rpx'}"
                  @click="toggleCategory(item)"
                >
                  <view class="category-node-left">
                    <text 
                      class="category-expand-icon" 
                      v-if="item.children && item.children.length > 0"
                    >
                      {{ item.expanded ? '▼' : '▶' }}
                    </text>
                    <text class="category-expand-icon-placeholder" v-else></text>
                    <radio 
                      :checked="tempSelectedCategory === item.value" 
                      :value="item.value"
                      color="#48eceb"
                    />
                    <text class="category-label">{{ item.label }}</text>
                  </view>
                </view>
                
                <!-- 二级分类 -->
                <block v-if="item.expanded && item.children">
                  <view 
                    v-for="(child, childIndex) in item.children" 
                    :key="childIndex"
                    class="category-node-wrapper"
                  >
                    <view 
                      class="category-node" 
                      :style="{paddingLeft: '60rpx'}"
                      @click="toggleCategory(child)"
                    >
                      <view class="category-node-left">
                        <text 
                          class="category-expand-icon" 
                          v-if="child.children && child.children.length > 0"
                        >
                          {{ child.expanded ? '▼' : '▶' }}
                        </text>
                        <text class="category-expand-icon-placeholder" v-else></text>
                        <radio 
                          :checked="tempSelectedCategory === child.value" 
                          :value="child.value"
                          color="#48eceb"
                        />
                        <text class="category-label">{{ child.label }}</text>
                      </view>
                    </view>
                    
                    <!-- 三级分类 -->
                    <block v-if="child.expanded && child.children">
                      <view 
                        v-for="(grandChild, grandChildIndex) in child.children" 
                        :key="grandChildIndex"
                        class="category-node-wrapper"
                      >
                        <view 
                          class="category-node" 
                          :style="{paddingLeft: '100rpx'}"
                          @click="toggleCategory(grandChild)"
                        >
                          <view class="category-node-left">
                            <text 
                              class="category-expand-icon" 
                              v-if="grandChild.children && grandChild.children.length > 0"
                            >
                              {{ grandChild.expanded ? '▼' : '▶' }}
                            </text>
                            <text class="category-expand-icon-placeholder" v-else></text>
                            <radio 
                              :checked="tempSelectedCategory === grandChild.value" 
                              :value="grandChild.value"
                              color="#48eceb"
                            />
                            <text class="category-label">{{ grandChild.label }}</text>
                          </view>
                        </view>
                        
                        <!-- 四级分类 -->
                        <block v-if="grandChild.expanded && grandChild.children">
                          <view 
                            v-for="(greatGrandChild, greatGrandChildIndex) in grandChild.children" 
                            :key="greatGrandChildIndex"
                            class="category-node-wrapper"
                          >
                            <view 
                              class="category-node" 
                              :style="{paddingLeft: '140rpx'}"
                            >
                              <view class="category-node-left">
                                <text class="category-expand-icon-placeholder"></text>
                                <radio 
                                  :checked="tempSelectedCategory === greatGrandChild.value" 
                                  :value="greatGrandChild.value"
                                  color="#48eceb"
                                />
                                <text class="category-label">{{ greatGrandChild.label }}</text>
                              </view>
                            </view>
                          </view>
                        </block>
                      </view>
                    </block>
                  </view>
                </block>
              </view>
            </block>
            </view>
          </radio-group>
        </scroll-view>
        
        <view class="category-modal-footer">
          <button class="category-modal-btn cancel" @click="showCategoryModal = false">取消</button>
          <button class="category-modal-btn confirm" @click="confirmCategory">确定</button>
        </view>
      </view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="bottom-actions">
      <button class="cancel-btn" @click="handleCancel">取消</button>
      <button class="save-btn" @click="handleSave">保存</button>
    </view>
  </view>
</template>

<script setup>
import http from '../../../utils/request'
import { ref, computed, watch } from 'vue'
import { callWorkflowListAPI, callWorkflowAPI } from '../../../utils/workflow'
import { useUserStore } from '../../../store/user'
import { useTaskStore } from '../../../store/task'
import { onLoad, onReady, onUnload, onShow, onBackPress } from '@dcloudio/uni-app'

const userStore = useUserStore()
const taskStore = useTaskStore()

// 表单数据
const formData = ref({
  supplier: '',
  brand: '',
  productName: '',
  salesUnit: '',
  boxSpec: '',
  barcode: '',
  category: '',
  storageType: '',
  auxiliaryCode: '',
  productType: '',
  storageCondition: '',
  shelfLifeUnit: '',
  shelfLife: '',
  weight: '',
  specLength: '',
  specWidth: '',
  specHeight: '',
  billingMethod: '',
  productImages: [],
  palletSpec: '',
  cost: '',
  needQualityCheck: ''
})

// 选项数据
const supplierOptions = ref([])
const supplierIndex = ref('')
const storageTypeOptions = ['重货', '抛货'] // 存储类型
const productTypeOptions = ['成品', '半成品'] // 商品类型
const shelfLifeUnitOptions = ['年', '月', '天', '无保质期'] // 保质期单位
const billingMethodOptions = ['按重量计费', '按体积计费', '按件计费'] // 计费方式
const needQualityCheckOptions = ['是', '否'] // 是否需要质检

// 存储条件选项
const storageConditionOptions = ['常温', '冷冻', '冷藏']

// 分类数据（从API动态获取）
const categoryData = ref([])

// 分类选择相关
const categoryText = ref('')
const showCategoryModal = ref(false)
const tempSelectedCategory = ref('')
const tempSelectedCategoryText = ref('')

// 选择器事件处理
const onStorageTypeChange = (e) => {
  formData.value.storageType = storageTypeOptions[parseInt(e.detail.value)]
}

const onProductTypeChange = (e) => {
  formData.value.productType = productTypeOptions[parseInt(e.detail.value)]
}

const onShelfLifeUnitChange = (e) => {
  formData.value.shelfLifeUnit = shelfLifeUnitOptions[parseInt(e.detail.value)]
}

const onBillingMethodChange = (e) => {
  formData.value.billingMethod = billingMethodOptions[parseInt(e.detail.value)]
}

const onNeedQualityCheckChange = (e) => {
  formData.value.needQualityCheck = needQualityCheckOptions[parseInt(e.detail.value)]
}

// 存储条件选择处理
const onStorageConditionChange = (e) => {
  formData.value.storageCondition = storageConditionOptions[parseInt(e.detail.value)]
}

// 打开分类弹窗
const openCategoryModal = () => {
  // 同步当前已选中的分类
  tempSelectedCategory.value = formData.value.category
  tempSelectedCategoryText.value = categoryText.value
  showCategoryModal.value = true
}

// 切换分类展开/收起状态
const toggleCategory = (category) => {
  if (category.children && category.children.length > 0) {
    category.expanded = !category.expanded
  }
}

// radio-group的change事件处理
const onRadioChange = (e) => {
  const selectedValue = e.detail.value
  console.log('Radio选择值:', selectedValue)
  
  // 根据value查找对应的分类对象
  const findCategory = (categories, value) => {
    for (const category of categories) {
      if (category.value === value) {
        return category
      }
      if (category.children && category.children.length > 0) {
        const found = findCategory(category.children, value)
        if (found) return found
      }
    }
    return null
  }
  
  const selectedCategory = findCategory(categoryData.value, selectedValue)
  if (selectedCategory) {
    tempSelectedCategory.value = selectedCategory.value
    tempSelectedCategoryText.value = selectedCategory.label
    console.log('选中分类:', selectedCategory.label, selectedCategory.value)
  }
}

// 确认分类选择
const confirmCategory = () => {
  if (tempSelectedCategory.value) {
    formData.value.category = tempSelectedCategory.value
    categoryText.value = tempSelectedCategoryText.value
    showCategoryModal.value = false
    console.log('确认选择分类:', categoryText.value, formData.value.category)
  } else {
    uni.showToast({
      title: '请选择一个分类',
      icon: 'none'
    })
  }
}

// 图片上传处理
const chooseImage = () => {
  uni.chooseImage({
    count: 9, // 最多选择9张图片（uni-app限制）
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      formData.value.productImages.push(...res.tempFilePaths)
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
  
    }
  })
}

// 预览图片
const previewImage = (index) => {
  uni.previewImage({
    urls: formData.value.productImages,
    current: index
  })
}

// 删除图片
const deleteImage = (index) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这张图片吗？',
    success: (res) => {
      if (res.confirm) {
        formData.value.productImages.splice(index, 1)
      }
    }
  })
}

// 表单验证
const validateForm = () => {
  if (supplierIndex.value === '') {
    uni.showToast({
      title: '请选择供应商',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.productName.trim()) {
    uni.showToast({
      title: '请输入商品名称',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.storageType.trim()) {
    uni.showToast({
      title: '请选择存储类型',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.productType.trim()) {
    uni.showToast({
      title: '请选择商品类型',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.shelfLifeUnit.trim()) {
    uni.showToast({
      title: '请选择保质期单位',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.shelfLife.trim()) {
    uni.showToast({
      title: '请输入保质期',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.weight.trim()) {
    uni.showToast({
      title: '请输入重量',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.specLength.trim()) {
    uni.showToast({
      title: '请输入规格长',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.specWidth.trim()) {
    uni.showToast({
      title: '请输入规格宽',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.specHeight.trim()) {
    uni.showToast({
      title: '请输入规格高',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.palletSpec.trim()) {
    uni.showToast({
      title: '请输入托规',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.cost.trim()) {
    uni.showToast({
      title: '请输入成本',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.value.billingMethod.trim()) {
    uni.showToast({
      title: '请选择计费方式',
      icon: 'none'
    })
    return false
  }
  
  return true
}

// 上传文件并获取URL
const uploadFileAndGetUrl = (filePath) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: 'https://api.shmodio.cn/uploadToCangdangxian', // 替换为实际的上传接口
      filePath: filePath,
      name: 'file',
       success: (res) => {
        try {
          console.log("上传文件成功", res);
          
          const data = JSON.parse(res.data);
          const url = data?.data?.fileUrl || data?.url;
          if (url) return resolve(url);
          reject(new Error(data?.message || '上传失败'));
        } catch {
          reject(new Error('响应解析失败'));
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
  
}

// 保存按钮点击事件
const handleSave = async () => {
 
  if (!validateForm()) {

    return
  }
    uni.showLoading({
      title: '处理中...',
      mask: true
    })
   
  // 这里可以调用API保存数据
  const imageUrls = await Promise.all(formData.value.productImages.map(uploadFileAndGetUrl))
  formData.value.productImages = imageUrls
  
  // 构建最终保存数据，去掉索引字段，只保留文本字段
  const saveData = {
    userRowid: userStore.getUserInfo().rowid,
    code:userStore.getWarehouseCode(),
    supplier: supplierOptions.value[supplierIndex.value],
    brand: formData.value.brand,
    productName: formData.value.productName,
    salesUnit: formData.value.salesUnit,
    boxSpec: formData.value.boxSpec,
    barcode: formData.value.barcode,
    category: formData.value.category,
    storageType: formData.value.storageType,
    auxiliaryCode: formData.value.auxiliaryCode,
    productType: formData.value.productType,
    storageCondition: formData.value.storageCondition,
    shelfLifeUnit: formData.value.shelfLifeUnit,
    shelfLife: formData.value.shelfLife,
    weight: formData.value.weight,
    specLength: formData.value.specLength,
    specWidth: formData.value.specWidth,
    specHeight: formData.value.specHeight,
    billingMethod: formData.value.billingMethod,
    productImages: formData.value.productImages,
    palletSpec: formData.value.palletSpec,
    cost: formData.value.cost,
    needQualityCheck: formData.value.needQualityCheck
  }
  

  
  
  console.log('保存商品数据:', saveData)
  console.log('新增商品保存地址:', userStore.getWarehouseInfo().gys_sp_create)
  
  try {
    const res =  await http.post(`https://www.dachen.vip/api/workflow/hooks/${userStore.getWarehouseInfo().gys_sp_create}`, saveData)
    console.log('新增商品成功:', res)

      uni.showToast({
    title: '保存成功',
    icon: 'success',
    success: () => {
       taskStore.setPendingTaskUpdate('add-product')
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  })
  } catch (error) {
    console.error('新增商品失败:', error)
    uni.showToast({
      title: '新增商品失败',
      icon: 'none'
    })
    return
  }




     uni.hideLoading()
}

// 取消按钮点击事件
const handleCancel = () => {
  uni.showModal({
    title: '提示',
    content: '确定要取消新增商品吗？',
    success: (res) => {
      if (res.confirm) {
        uni.navigateBack()
      }
    }
  })
}

const getSupplier = async () => {
  try {
      const res = await callWorkflowListAPI('gonghuoshang')
  if(res){
    console.log('供应商', res.data);
    const filteredSuppliers = res.data.filter(item => {
      return JSON.parse(userStore.getUserInfo()['68ea18b6470b6cef2f580870']).includes(item.rowid)
    })
    
    supplierOptions.value = filteredSuppliers.map(item => {
      return item['68639102a4471151d6aaa98b']
    })
    
    // 自动设置第一个供应商
    if (filteredSuppliers.length > 0) {
      supplierIndex.value = 0
      formData.value.supplier = supplierOptions.value[0]
      console.log('自动设置第一个供应商:', supplierOptions.value[0])
    }
    
  }
  } catch (error) {
    console.error('获取供应商失败:', error)
  }
  
}

// 构建分类树形结构
const buildCategoryTree = (data) => {
  // 创建一个映射表，用于快速查找
  const itemMap = new Map()
  const tree = []
  
  // 第一步：将所有数据放入映射表
  data.forEach(item => {
    const name = item['68fadbefa97f0a4efae4dfe7'] // 类目名称
    const parentName = item['68fadbefa97f0a4efae4dfe8'] // 上级物料名称
    
    itemMap.set(name, {
      label: name,
      value: item.rowid,
      parentName: parentName || null,
      children: [],
      expanded: false
    })
  })
  
  console.log('所有分类名称:', Array.from(itemMap.keys()))
  
  console.log('itemMap键值对:')
  itemMap.forEach((value, key) => console.log(`${key}:`, value))
  
  // 第二步：构建树形结构
  itemMap.forEach((item) => {
    if (!item.parentName) {
      // 没有上级物料名称，是一级分类
      tree.push(item)
    } else {
      // 有上级物料名称，找到父节点并添加为子节点
      const parent = itemMap.get(item.parentName)
      if (parent) {
        parent.children.push(item)
      } else {
        // 如果找不到父节点，作为一级分类处理
        console.warn(`警告: "${item.label}" 的父节点 "${item.parentName}" 不存在，将其作为一级分类`)
        tree.push(item)
      }
    }
  })
  
  // 第三步：清理空的children数组
  const cleanEmptyChildren = (nodes) => {
    nodes.forEach(node => {
      if (node.children && node.children.length === 0) {
        delete node.children
      } else if (node.children) {
        cleanEmptyChildren(node.children)
      }
    })
  }
  cleanEmptyChildren(tree)
  
  return tree
}

const getCeshi = async () => {
  try {
  

    const res = await callWorkflowListAPI('68fadbefa97f0a4efae4dfe6',[])
    const rows = res.data
    
    console.log('原始分类数据', rows)
    
    // 构建分类树
    const tree = buildCategoryTree(rows)
    console.log('构建的分类树', tree)
    
    // 更新分类数据
    categoryData.value = tree
    
    // 初始化展开状态
    initCategoryExpanded(categoryData.value)
    
  } catch (error) {
    console.log('获取分类数据失败', error)
    uni.showToast({
      title: '获取分类数据失败',
      icon: 'none'
    })
  }
}

// 初始化分类数据的展开状态
const initCategoryExpanded = (categories) => {
  categories.forEach(category => {
    category.expanded = false
    if (category.children && category.children.length > 0) {
      initCategoryExpanded(category.children)
    }
  })
}

onLoad(async () => {
  // 显示加载动画
  uni.showLoading({
    title: '加载中...',
    mask: true
  })
  
  try {
    // 并发加载所有数据
    await Promise.all([
      getCeshi(),
      getSupplier()
    ])
    
    console.log('所有数据加载完成')
  } catch (error) {
    console.error('数据加载失败:', error)
    uni.showToast({
      title: '数据加载失败',
      icon: 'none'
    })
  } finally {
    // 关闭加载动画
    uni.hideLoading()
  }
})
</script>

<style lang="scss" scoped>
.add-product-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}


.form-scroll {
  flex: 1;
  background-color: #ffffff;
}

.section {
  padding: 30rpx;
  border-bottom: 20rpx solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
  }
  
  .section-title {
    margin-bottom: 30rpx;
    padding-left: 20rpx;
    border-left: 6rpx solid #48eceb;
    
    .section-title-text {
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
    }
  }
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .label {
    font-size: 30rpx;
    color: #666666;
    min-width: 200rpx;
    flex-shrink: 0;
    
    &.required::before {
      content: '*';
      color: #ff4757;
      margin-right: 4rpx;
    }
  }
  
  .input {
    flex: 1;
    background-color: #f8f8f8;
    border-radius: 8rpx;
    padding: 20rpx;
    font-size: 28rpx;
    color: #333333;
    margin-right: 10rpx;
    
    &::placeholder {
      color: #999999;
    }
  }
  
  .unit {
    font-size: 28rpx;
    color: #666666;
    margin-left: 10rpx;
  }
  
  .picker {
    flex: 1;
    
    .picker-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #f8f8f8;
      border-radius: 8rpx;
      padding: 20rpx;
      
      .picker-text {
        font-size: 28rpx;
        color: #333333;
      }
      
      .picker-arrow {
        font-size: 28rpx;
        color: #999999;
      }
    }
  }
  
  // 图片上传样式
  .image-upload-item {
    align-items: flex-start;
  }
  
  .image-upload-container {
    flex: 1;
  }
  
  .image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    margin-bottom: 10rpx;
  }
  
  .image-item {
    position: relative;
    width: 160rpx;
    height: 160rpx;
  }
  
  .uploaded-image {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
    object-fit: cover;
  }
  
  .delete-btn {
    position: absolute;
    top: -10rpx;
    right: -10rpx;
    width: 40rpx;
    height: 40rpx;
    background-color: #ff4757;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .delete-icon {
      color: #ffffff;
      font-size: 24rpx;
      font-weight: bold;
    }
  }
  
  .upload-btn {
    width: 160rpx;
    height: 160rpx;
    border: 2rpx dashed #cccccc;
    border-radius: 8rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f8f8f8;
    
    .upload-icon {
      font-size: 48rpx;
      color: #999999;
      margin-bottom: 10rpx;
    }
    
    .upload-text {
      font-size: 24rpx;
      color: #999999;
    }
  }
  

}

.bottom-spacing {
  height: 120rpx;
}

// 分类弹窗样式
.category-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.category-modal-content {
  width: 90%;
  max-height: 80vh;
  background-color: #ffffff;
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.category-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.category-modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.category-modal-close {
  font-size: 48rpx;
  color: #999999;
  line-height: 1;
}

.category-modal-body {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx 0;
}

.category-tree {
  width: 100%;
}

.category-node-wrapper {
  width: 100%;
}

.category-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  min-height: 88rpx;
}

.category-node-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.category-expand-icon {
  font-size: 24rpx;
  color: #666666;
  margin-right: 20rpx;
  width: 30rpx;
  text-align: center;
}

.category-expand-icon-placeholder {
  width: 50rpx;
  display: inline-block;
}

.category-label {
  font-size: 28rpx;
  color: #333333;
  margin-left: 20rpx;
}

.category-modal-footer {
  display: flex;
  justify-content: space-between;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.category-modal-btn {
  width: 48%;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  line-height: 80rpx;
  
  &.cancel {
    background-color: #ffffff;
    color: #666666;
    border: 2rpx solid #cccccc;
  }
  
  &.confirm {
    background: linear-gradient(to right, #48eceb, #0fcee9);
    color: #ffffff;
    border: none;
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  z-index: 100;
  
  .cancel-btn {
    width: 45%;
    background-color: #ffffff;
    color: #666666;
    border: 2rpx solid #cccccc;
    border-radius: 32rpx;
    font-size: 32rpx;
    height: 88rpx;
  }
  
  .save-btn {
    width: 45%;
    background: linear-gradient(to right, #48eceb, #0fcee9);
    color: #ffffff;
    border: none;
    border-radius: 32rpx;
    font-size: 32rpx;
    font-weight: bold;
    height: 88rpx;
  }
}
</style>